function [idat sandbox] = fsb_reslice(idat,sandbox)

% FSB - SPM:  reslice all volumes within a dataset with the spatial
% transforms in the .mat or .nii file
%
% EXAMPLE:
% fsb_reslice(file_names,rea_par)
%
% INPUT
% A list of file names (file_names)
% A parameter struct rea_par with the fields
% rea_par.rp
%
%
% OUTPUT:
% Realigned volume stack
% NOTES:
%
% External files:
% spm2_realign.m : Does the actual realignment in SPM2, just renamed
% fsb_load_files.m : Simple file loading function
% fsb_realing_yonly:
%
%
%$ Revision 1.0
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

newpath = 'spm_temp';
%name = [sandbox.name(1:2) '_'];
mkdir (newpath); cd (newpath);

dim = size(idat);

if size(dim,2)<4;
    dim(4) = 1;
end

% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
% write images 
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

%fsb_img_write(idat,'temp',sandbox.hdr,4,1);
% fsb_mat_write(idat,sandbox.hdr);


fsb_nii_write(idat,'temp0001',sandbox.hdr,4,1);
fsb_nii_write(idat,'temp0002',sandbox.hdr,4,1);
fsb_nii_write(idat,'temp0003',sandbox.hdr,4,1);

 %set_spm2_path;
 %rehash;
global defaults
warning off; % Suppress warning about flipped image orientation

%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
% Get files
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

P = fsb_get_files_SPM('t');

%P = P(1:end-2);



%reslice_nii(P, 'temp2.nii', [sandbox.hdr.dime.pixdim(2:4)]);
%reslice_nii(P, 'temp2.nii');

P = spm_vol(P);
dim(4) = size(P,1);
% 
for x = 1:dim(4)
    
    P(x).mat(1,:) = sandbox.hdr.hist.srow_x;
    P(x).mat(2,:) = sandbox.hdr.hist.srow_y;
    P(x).mat(3,:) = sandbox.hdr.hist.srow_z;
end

%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
% Start SPM figures
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

G = spm_figure('GetWin','Graphics');
F = spm_figure('GetWin','Interactive');
fg = spm_figure('FindWin','Interactive');

%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
%  reslice all images
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
spm_progress_bar('clear');
spm_progress_bar('init');
reslice_flags = struct('interp',4,'mask',0,'mean',0,'which',2,'wrap',[0 0 0]'); % reslice images
%spm_reslice(P_rea,reslice_flags);

spm_reslice(P,reslice_flags);
spm_progress_bar('clear');
P_rea = fsb_get_files_SPM('r');
file_names = P_rea(:,1:end-2);
file_names = cellstr(file_names)';
close(fg);
close(G);

[idat sandbox] = fsb_load_files(file_names(3));
cd ..
rmdir(newpath,'s');

disp('Reslicing : Done');
end

